package ch.bfh.swos.learnaid.service.impl;

import java.lang.reflect.Type;
import java.util.Collection;

import javax.inject.Inject;
import javax.inject.Named;

import org.modelmapper.ModelMapper;
import org.modelmapper.TypeToken;

import ch.bfh.swos.learnaid.model.QList;
import ch.bfh.swos.learnaid.repository.QListRepository;
import ch.bfh.swos.learnaid.service.QListService;
import ch.bfh.swos.learnaid.service.dto.QListDTO;

@Named
public class DefaultQListService implements QListService {
    
    @Inject
    private QListRepository qListRepository;
    
    private final ModelMapper mapper = new ModelMapper();

    @Override
    public QListDTO create(QListDTO qListDTO) {
        QList qList = mapper.map(qListDTO, QList.class);
        QList persitedQList = qListRepository.save(qList);
        return mapper.map(persitedQList, QListDTO.class);
    }

    @Override
    public QListDTO read(long id) {
        QList list = qListRepository.findOne(id);
        if (list != null) {
            return mapper.map(list, QListDTO.class);
        }
        return null;
    }

    @Override
    public Collection<QListDTO> list() {
        Iterable<QList> qlists = qListRepository.findAll();
        Type listType = new TypeToken<Collection<QListDTO>>(){
        }.getType();
        return mapper.map(qlists,listType);
    }

    @Override
    public QListDTO update(QListDTO qListDTO) {
        QList qList = mapper.map(qListDTO, QList.class);
        QList updatedQList = qListRepository.save(qList);
        return mapper.map(updatedQList, QListDTO.class);
    }

    @Override
    public void delete(QListDTO qListDTO) {
        QList qList = qListRepository.findOne(qListDTO.getId());
        qListRepository.delete(qList);

    }

}
